package cn.restcloud.example.ssofilter;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import cn.restcloud.framework.core.context.AppContext;
import cn.restcloud.framework.core.context.AppThreadManager;
import cn.restcloud.framework.core.util.CommonUtil;
import cn.restcloud.framework.core.util.ConfigUtil;
import cn.restcloud.framework.core.util.PrintUtil;
import cn.restcloud.framework.login.service.JwtTokenService;
import cn.restcloud.springboot.config.SpringbootWebMvcConfig;
import java.io.IOException;

public class SSOLoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

    	//只要这里设置用户名就可以让用户直接登录,用户数据也需注册到平台中
    	HttpServletRequest request=(HttpServletRequest) servletRequest;
    	HttpServletResponse response=(HttpServletResponse) servletResponse;
    	String url = request.getRequestURI();//访问地址:http://localhost/restcloud/rest/appid/test.do得到/rest/appid/test.do
    	if(url.startsWith(SpringbootWebMvcConfig.getRootPath())) {
    		url=StringUtils.substringAfter(url, SpringbootWebMvcConfig.getRootPath());
    	}
    	if(AppThreadManager.getLoginUrls().contains(url)) {
    		try {
	    		//如果用户请求的是登录地址login地址，则进行用户认证
	        	String userId=request.getParameter("userName");
	        	String password=request.getParameter("password");
	        	if(password.equals(CommonUtil.md5("123"))) {
	        		//认证通过
	        		AppContext.setUserId(userId);
	        		
	    			//增加登录成功后的cookie
	    			String identitytoken="";
					
						 //给此用户生成一个token
						identitytoken = JwtTokenService.getToken(userId,"","1");
		    			Cookie cookie = new Cookie(JwtTokenService.TOKENKEY, identitytoken);
		    			String cookieDomain=ConfigUtil.getConfig("CookieDomain");
		    			if(StringUtils.isNotBlank(cookieDomain)){
		    				cookie.setDomain(cookieDomain);
		    			}
		    			cookie.setPath("/");
		        		response.addCookie(cookie);
		        		
		    			Cookie cookie2 = new Cookie("userName",userId); //写一个cookie到浏览器中
		    			cookie2.setDomain(cookieDomain);
		    			cookie2.setPath("/");
		    			response.addCookie(cookie2);
		    			
		    			//登录成功返回token
		    			response.setHeader("Content-type", "application/json;charset=utf-8");
		    			response.getWriter().print("{\"state\":true,\"userId\":\""+userId+"\",\"userName\":\""+userId+"\",\""+JwtTokenService.TOKENKEY+"\":\""+identitytoken+"\"}");
		    			PrintUtil.o(userId+"登录成功...............");
		    			return;
	        	}else {
	        		response.setHeader("Content-type", "application/json;charset=utf-8");
	    			response.getWriter().print("{\"state\":false,\"msg\":\"用户SSO登录失败\"}");
	    			return;
	        	}
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}else {
    		//说明用户已经登录，直接从SSO拿用户名
    		String userId=request.getRemoteUser();
    		if(StringUtils.isNotBlank(userId)) {
    			PrintUtil.o("用户已经从SSO中登录过了，userId=="+userId);
    			AppContext.setUserId(userId);
    		}
    	}
    	
    	//继续执行
        filterChain.doFilter(servletRequest, servletResponse);
        
    }

    @Override
    public void destroy() {

    }
}